﻿/**
 * @class Domain
 */
core.Domain = {
  _crossed: false,
  _cross: function(){
    try{document.domain = window.location.hostname.split('.').reverse().slice(0,2).reverse().join('.');this._crossed = true;}catch(e){};
  },
  _needCross: function(host){
    return host != location.hostname;
  },
  _root: function(host){
    if(!host) {
      host = location.protocol + "//" + location.hostname;
      if(location.port) host += ":" + location.port;
    }
    return host.replace(/(https?:\/\/)?([^\/]+)(\s|\S)*/g, "$2");
  },
  proxies: {},
  init: function(hosts, callback){
    var that = this, hostarr = hosts.split(",");
    for(var i=0;i<hostarr.length;i++){
      var hostname = hostarr[i];
      if(that._needCross(hostname)){
        if(!that._crossed) that._cross();
        if(that.proxies[hostname]) {
          (function() {
            if (that.proxies[hostname].loaded) {
              if(callback) callback.call(that, hostname);
            } else {
              setTimeout(arguments.callee, 100);
            }
          })();
        } else {
          var iframe = document.createElement('iframe');
          iframe.style.display = 'none';
          document.body.insertBefore(iframe, document.body.firstChild);
          iframe.src = 'http://' + hostname + '/ajaxproxy.html';
          that.proxies[hostname] = iframe;
          that.proxies[hostname].loaded = false;
          var onloadEvent = function(){
            if (iframe.contentWindow.location.href !== iframe.src) {
              iframe.contentWindow.location.href = iframe.src;
            } else {
              //iframe load完成，修改状态属性
              that.proxies[hostname] = iframe;
              that.proxies[hostname].loaded = true;
              if(callback) callback.call(that, hostname);
            }
          };
          if (iframe.attachEvent) {
            iframe.attachEvent('onload', onloadEvent);
          } else {
            iframe.onload = onloadEvent;
          }
        }
      }
    }
  },
  use: function(hostname, callback){
    var that = this;
    if(!that.proxies.xhr) that.proxies.xhr = jQuery.ajaxSettings.xhr;
    if(that._needCross(hostname)){
      if(that.proxies[hostname] && that.proxies[hostname].loaded){
        $.ajaxSetup({
          crossDomain: false,
          xhr: function(){
            if(this.dataType == "script") return that.proxies.xhr();
            if(that._root(this.url) == location.hostname){
              return that.proxies.xhr();
            } else {
              return that.proxies[hostname].contentWindow.getTransport();
            }
          }
        });
        if(callback) callback.call(this);
      }else{
        core.Domain.init(hostname, function(host){
          core.Domain.use(host, callback);
        });
      }
    } else {
      if(callback) callback.call(this);
    }
  }
};
